<?php
	class Sss_Ultility_AdministrationFunction extends Ovis_Controller {
		function deleteUser($account, $accountId,$accountTable)
		{
			$result = Resources::_('DELETE_USER_FAIL');
			$accountUpdate = $accountTable->findById((int) $accountId);
			$accountUpdate->setAccountId((int) $accountId);
			$accountUpdate->setIsarchived(1);
			$deleteId = $accountTable->save($accountUpdate);
			if (isset($deleteId)) {
				//Delete user in OTRS service when delete user in ovis site
				$otrs = new Sss_Ultility_OtrsServices();
				if($account){
					$fullName = $account->fullname;
					$userName = $account->username.$accountId;
					$email = $accountId.$account->email;
					$otrs->deleteUser($account->otrs_user_id, USER_SERVICE_ID, 2, $fullName, $userName, $email, USER_SERVICE, PASSWORD_SERVICE);
				}
				$result = Resources::_('DELETE_USER_SUCCESSFULL');
			}
			return $result;
		}
		function getQueyString($isSearch, $filterParam)
		{
			$orderQueryString = '';
			$queryString = '';
			if ($isSearch) {
				$queryString .= '&s=1';
				$orderQueryString = '&' . Sss_Ultility_CommonViewParamater::PAGE . '=' . $filterParam[Sss_Ultility_CommonViewParamater::PAGE] . '&s=1';
			} else {
				$orderQueryString = '&' . Sss_Ultility_CommonViewParamater::PAGE . '=' . $filterParam[Sss_Ultility_CommonViewParamater::PAGE];
			}
			if (!is_null($filterParam[Sss_Ultility_CommonViewParamater::ORDERFIELD])) {
				$queryString .= '&' . Sss_Ultility_CommonViewParamater::ORDERFIELD . '=' . $filterParam[Sss_Ultility_CommonViewParamater::ORDERFIELD];
			}
			if (!is_null($filterParam[Sss_Ultility_CommonViewParamater::ORDERTYPE])) {
				$queryString .= '&' . Sss_Ultility_CommonViewParamater::ORDERTYPE . '=' . $filterParam[Sss_Ultility_CommonViewParamater::ORDERTYPE];
			}
			$arrQueryString = array();
			$arrQueryString['querystring'] = $queryString;
			$arrQueryString['oquerystring'] = $orderQueryString;
			return $arrQueryString;
		}
		function resetPassword($account, $params, $resetId, $handle = null)
		{
			if ($handle != null) {
				$accountTable = new Shepherd_Model_Mapper_Account();
				$handle = "/$handle";
				$subject = Resources::_('SUBJECT_RESET');
				$shepherd = true;
			} else {
				$accountTable = new Application_Model_Mapper_Account();
				$subject = Resources::_('OVIS_SUBJECT_RESET');
				$shepherd = false;
			}
			
			$activateCode   = Sss_Ultility_Common::genRandomString(75);
			$email             = $account->email;
			//$accountId = $accountTable->updateData($arrAccountId, $data, $shepherd);
			$body    = Resources::_('DEAR').' '.$account->fullname.',' . " \n \n"
			.Resources::_('BODY1'). " \n \n"
			.Resources::_('BODY2').' '.DOMAIN_SYSTEM."$handle/active/active?activatecode=$activateCode&popup=1&resetpassword=1". " \n \n"
			.Resources::_('BODY4'). " \n \n"
			.Resources::_('BODY5'). " \n"
			.Resources::_('BODY6');

			Sss_Ultility_Common::sendMail(EMAIL_SYSTEM, $email, $subject, $body);

			return Resources::_('RESET_PASSWORD_SUCCESSFULL');
		}
		function processOTRSAccount($params, $accountId, $userOtrsId, $type, $passWordDefault, $otrs)
		{
			$accountTable = new Application_Model_Mapper_Account();
			$instanceTable = new Application_Model_Mapper_Instance();
			$vendorAccountTable = new Application_Model_Mapper_VendorAccount();
			$vendorAccountContructor = new Application_Model_VendorAccount();

			//Update OTRS id
			$accountUpdate = $accountTable->findById($accountId);
			$accountUpdate->setOtrsUserId($userOtrsId);
			$accountTable->save($accountUpdate);

			//When create new ovis account and assign this ovis account to all group OTRS of instance
			if($type == Sss_Ultility_Setting::ACCOUNT_OVIS){
				$instances = $instanceTable->getConectedInstanceList();
				foreach($instances as $instance){
					if(!is_null($instance['otrs_group'])) {
						$otrs->assignUser2Group(USER_SERVICE_ID,$userOtrsId, null, $instance['otrs_group'], USER_SERVICE, PASSWORD_SERVICE);
					}
				}
			}
			if(isset($params['vendorid']) && !empty($params['vendorid'])) {
				$vendorAccountContructor->setAccount($accountId);
				$vendorAccountContructor->setVendor($params['vendorid']);
				$vendorAccountTable->save($vendorAccountContructor);
			}

			$activateCode   = Sss_Ultility_Common::genRandomString(75);
			$email             = $params['email'];
			$data              = array(
			'activatecode' => $activateCode
			);

			//Process password user
			$arrAccountId = array(
			'accountid' => $accountId
			);
			$accountUpdate->setActivateCode($activateCode);
			$accountId = $accountTable->save($accountUpdate);

			$subject = Resources::_('OVIS_SUBJECT_ADD');
			$body =  $body    = Resources::_('DEAR').' '.$params['fullname'].',' . " \n \n"
			. Resources::_('OVIS_BODY_ADD') . " \n \n"
			. Resources::_('PASSWORD') . ": ". $passWordDefault . " \n \n"
			. Resources::_('BODY14_1'). " \n \n"
			. Resources::_('BODY5'). " \n"
			. Resources::_('BODY6');

			$body    = Resources::_('DEAR').' '.$params['fullname'].',' . " \n \n"
			. Resources::_('OVIS_BODY_ADD') . " \n \n"
			. Resources::_('BODY2').' '.DOMAIN_SYSTEM."/active/active?activatecode=$activateCode&popup=1"." \n \n"
			. Resources::_('USERNAME').' '. $params['username']
			. " \n"
			. Resources::_('PASSWORD') . ": ". $passWordDefault. " \n \n"
			. Resources::_('BODY14_1'). " \n \n"
			. Resources::_('BODY5'). " \n"
			. Resources::_('BODY6');

			Sss_Ultility_Common::sendMail(EMAIL_SYSTEM, $email, $subject, $body);
			return Resources::_('ADD_USER_SUCCESSFULL');
		}
		function checkUserExist($list, $params)
		{
			$message = null;
			//Process adding new user
			foreach ($list as $l) {
				if (trim($l['username']) == trim($params['username'])) {
					$message = Resources::_('USER_NAME_EXIST');
					return $message;
				}
				if (trim($l['email']) == trim($params['email'])) {
					$message = Resources::_('EMAIL_EXIST');
					return $message;
				}
			}
			return $message;
		}
		function processCompanyOwner($row)
		{
			$accountTable = new Application_Model_Mapper_Account();
			$listCompnayOwner    = array();
			$listCompnayOwnerId = array();
			foreach ((array) $row as $r) {
				//get company owner account name by stock location
				$compnayOwner           = $accountTable->getCompanyOwnerByStockLocation($r['stocklocation']);
				$compnayOwnerName = '';
				$arrCompanyOwnerId = array();
				if(count($compnayOwner) > 0) {
					foreach($compnayOwner as $c){
						if($compnayOwnerName != '') {
							$compnayOwnerName = $compnayOwnerName.', ';
						}
						$compnayOwnerName = $compnayOwnerName.$c['fullname'];
						$arrCompanyOwnerId[] = $c['companyowner'];
					}
					$listCompnayOwner[] = $compnayOwnerName;
					$listCompnayOwnerId[] = $arrCompanyOwnerId;
				} else {
					$listCompnayOwnerId[] = '';
					$listCompnayOwner[] = $compnayOwnerName;
				}
			}
			$result = array();
			$result['listcompnayownerid'] = $listCompnayOwnerId;
			$result['listcompnayowner'] = $listCompnayOwner;
			return $result;
		}
		function addInstance($instanceTable,$params)
		{
			$accountTable = new Application_Model_Mapper_Account();
			$instanceContructor = new Application_Model_Instance();
			$createBy = $userInformation['accountid'];
			$fullPath = null;
			$fileName = $_FILES[Sss_Ultility_CommonViewParamater::FILE_UPLOAD][Sss_Ultility_CommonViewParamater::NAME];
			if ($fileName) {
				$filePath = $_FILES[Sss_Ultility_CommonViewParamater::FILE_UPLOAD][Sss_Ultility_CommonViewParamater::TMP_NAME];
				$newPath  = Sss_Ultility_CommonViewParamater::FILE_PATH_LOGO . $fileName;
				move_uploaded_file($filePath, $newPath);
				$fullPath     = '/' . Sss_Ultility_CommonViewParamater::FILE_PATH_LOGO . $fileName;
			}

			$handleInstance = addslashes($params['handle']);
			// Call OTRS service and create new group when add new shepherd instance
			$otrs = new Sss_Ultility_OtrsServices();
			$groupId = $otrs->createGroup(USER_SERVICE_ID, 1, $handleInstance, '', USER_SERVICE, PASSWORD_SERVICE);
			if (is_null($groupId)) {
			$msg =  Resources::_('HANDLE_NAME_EXIST');
			$this->view->assign(Sss_Ultility_CommonViewParamater::MSG, $msg);
			Sss_Ultility_Common::logger()->log($msg, Zend_Log::ERR);
			}
			$otrs->addQueue(USER_SERVICE_ID, 1, $handleInstance, $groupId, USER_SERVICE, PASSWORD_SERVICE);
			// Call service of OTRS and update all ovis account to group when add new shepherd instance
			$accounts = $accountTable->getAccountListByType(Sss_Ultility_Setting::ACCOUNT_OVIS);
			foreach($accounts as $account){
				if(!is_null($account['otrs_user_id'])){
					$otrs->assignUser2Group(USER_SERVICE_ID,$account['otrs_user_id'], null, $groupId, USER_SERVICE, PASSWORD_SERVICE);
				}
			}
			$stockLocationIds = explode('_', $params['stocklocation']);
			
			// Assign company owner of instance to OTRS group
			$companyOwners = $accountTable->getCompanyOwnerByStockLocation($stockLocationIds[0]);
			if(count($companyOwners) > 0){
				foreach($companyOwners as  $companyOwner){
					if(!is_null($companyOwner['otrs_user_id'])){
						$otrs->assignUser2Group(USER_SERVICE_ID,$companyOwner['otrs_user_id'], null, $groupId, USER_SERVICE, PASSWORD_SERVICE);
					}
				}
			}
			$connect = isset($params['connected']) ? 1 : 0;
			$instanceContructor->setInstanceName(addslashes($params['instancename']));
			$instanceContructor->setHandle($handleInstance);
			$instanceContructor->setEmail(addslashes($params['email']));
			$instanceContructor->setStockLocation($stockLocationIds[0]);
			$instanceContructor->setLogo($fullPath);
			$instanceContructor->setCreatedBy($createBy);
			$instanceContructor->setCreatedDate(Sss_Ultility_Common::getDateTimeNumber());
			$instanceContructor->setUpdatedBy($createBy);
			$instanceContructor->setUpdatedDate(Sss_Ultility_Common::getDateTimeNumber());
			$instanceContructor->setConnected($connect);
			$instanceContructor->setOtrsGroup($groupId);
			//Process adding new instance
			$id = $instanceTable->save($instanceContructor);
			return $id;
		}
		function addStockLocationToInstance($id,$arrStockLocationId,$handleInstance,$params)
		{
			$stockLocationInstanceTable = new Application_Model_Mapper_StockLocationInstance();
			$stockLocationTable = new Application_Model_Mapper_StockLocation();
			$instanceTable = new Application_Model_Mapper_Instance();
			$message = '';
			if (false != $arrStockLocationId) {
				for ($i = 0; $i < count($arrStockLocationId); $i++) {
					$stockLocationId = $arrStockLocationId[$i];
					if ($stockLocationId > 0 && $stockLocationId != '') {
						$stockLocationInstanceContructor = new Application_Model_StockLocationInstance();
						$stockLocationInstanceContructor->setStockLocation($stockLocationId);
						$stockLocationInstanceContructor->setInstance($id);
						$stockLocationInstanceTable->save($stockLocationInstanceContructor);
					}
				}
			}
			$newDBName = SHEPHERD_SUFIX . Sss_Ultility_Common::formatString($id, 3);
			try {
				Sss_Ultility_Common::generateDatabase($newDBName);
				$accountTable      = new Shepherd_Model_Mapper_Account();
				$accountContructor = new Shepherd_Model_Account();
				$passWordDefault   = Sss_Ultility_Common::genRandomString();
				$userNameDefault   = Sss_Ultility_CommonViewParamater::USER_NAME_SHEPHERD_DEFAULT;
				$encryptedPassword = Sss_Crypt::factory()->encrypt("$passWordDefault");
				$email             = $params['email'];
				$arrParams = array();
				$arrParams['fullname'] =  Sss_Ultility_CommonViewParamater::USER_NAME_SHEPHERD_DEFAULT;
				$arrParams['username'] =  Sss_Ultility_CommonViewParamater::USER_NAME_SHEPHERD_DEFAULT.$id.$handleInstance;
				$arrParams['password'] =  $encryptedPassword;
				$arrParams['email']    =  $id.$handleInstance.$email;
				$arrParams['wsuser']   =  USER_SERVICE;
				$arrParams['wspass']   =  PASSWORD_SERVICE;
				$otrs->createCustomerUser(USER_SERVICE_ID, 1, $arrParams);
			
				$otrs->assignCustomer2Group(USER_SERVICE_ID, Sss_Ultility_CommonViewParamater::USER_NAME_SHEPHERD_DEFAULT.$id.$handleInstance, null, $groupId, USER_SERVICE, PASSWORD_SERVICE);
				$accountContructor->setUsername($userNameDefault);
				$accountContructor->setFullname($userNameDefault);
				$accountContructor->setPassword($encryptedPassword);
				$accountContructor->setEmail($email);
				$accountContructor->setIsActivated(1);
				$accountContructor->setIsArchived(0);
				$accountContructor->setIsBlock(0);
				$accountContructor->setSalt('');
				$accountContructor->setIsSystem(1);
				//Process adding new user default
				$accountTable->save($accountContructor, $id);
			
				$subject   = Resources::_('SUBJECT');
				$body      = Resources::_('BODY') . " \n \n" . Resources::_('USERNAME') . ": $userNameDefault \n" . Resources::_('PASSWORD') . ": $passWordDefault ";
			
				Sss_Ultility_Common::sendMail(EMAIL_SYSTEM, $email, $subject, $body);
			
				if (false != $stockLocationIds) {
					for ($i = 0; $i < count($stockLocationIds); $i++) {
						$stockLocationId = $stockLocationIds[$i];
						if ($stockLocationId > 0 && $stockLocationId != '') {
							$stockUpdate = $stockLocationTable->findById($stockLocationId);
							$stockUpdate->setShepherd(1);
							$stockLocationTable->save($stockUpdate);
						}
					}
				}
				$message = Resources::_('ADD_INSTANCE_SUCCESSFULL');
			} catch (Exception $e) {
				Sss_Ultility_Common::logger()->log($e, Zend_Log::ERR);
				$instance = $instanceTable->getById($id);
				if ($instance->logo && file_exists(getcwd() . $instance->logo))
					unlink(getcwd() . $instance->logo);

				//delete instance
				$instanceTable->deleteRow(( int ) $id);
				$message = Resources::_('ADD_INSTANCE_FAIL');
				//grop database with instance deleted
				Sss_Ultility_Common::dropDatabase($newDBName);
			}
			return $message;
		}
		function editInstance($userInformation,$instanceTable,$stockLocationTable,$stockLocationInstanceTable,$params,$instanceId,$stockLocation)
		{
			$createBy = $userInformation['accountid'];
			$accountTable = new Application_Model_Mapper_Account();
			$fullPath = null;
			$fileName = $_FILES[Sss_Ultility_CommonViewParamater::FILE_UPLOAD][Sss_Ultility_CommonViewParamater::NAME];
			$connect = isset($params['connected']) ? 1 : 0;
			$instanceUpdate = $instanceTable->findById($instanceId);
			$instanceUpdate->setInstanceName(addslashes($params['instancename']));
			$instanceUpdate->setHandle(addslashes($params['handle']));
			$instanceUpdate->setEmail(addslashes($params['email']));
			$instanceUpdate->setStockLocation($stockLocation);
			$instanceUpdate->setUpdatedBy($createBy);
			$instanceUpdate->setUpdatedDate(Sss_Ultility_Common::getDateTimeNumber());
			$instanceUpdate->setConnected($connect);
			if ($fileName) {
				if ($instance->logo) {
					if (file_exists(getcwd() . $instance->logo))
						unlink(getcwd() . $instance->logo);
				}
				$filePath = $_FILES[Sss_Ultility_CommonViewParamater::FILE_UPLOAD][Sss_Ultility_CommonViewParamater::TMP_NAME];
				$newPath  = Sss_Ultility_CommonViewParamater::FILE_PATH_LOGO . $fileName;
			
				move_uploaded_file($filePath, $newPath);
				$fullPath     = '/' . Sss_Ultility_CommonViewParamater::FILE_PATH_LOGO . $fileName;
			
				$instanceUpdate->setLogo($fullPath);
			}
				
			if (is_null($instance->otrs_group)) {
				$handleInstance = addslashes($params['handle']);
				// Call OTRS service and create new group when add new shepherd instance
				$otrs = new Sss_Ultility_OtrsServices();
				 $groupId = $otrs->createGroup(USER_SERVICE_ID, 1, $handleInstance, '', USER_SERVICE, PASSWORD_SERVICE);
				$otrs->addQueue(USER_SERVICE_ID, 1, $handleInstance, $groupId, USER_SERVICE, PASSWORD_SERVICE);
				// Call service of OTRS and update all ovis account to group when add new shepherd instance
				$accounts = $accountTable->getAccountListByType(Sss_Ultility_Setting::ACCOUNT_OVIS);
				foreach($accounts as $account){
					if(!is_null($account['otrs_user_id'])){
					$otrs->assignUser2Group(USER_SERVICE_ID,$account['otrs_user_id'], null, $groupId, USER_SERVICE, PASSWORD_SERVICE);
					}
				}
				$stockLocationIds = explode('_', $params['stocklocation']);
				// Assign company owner of instance to OTRS group
				$companyOwners = $accountTable->getCompanyOwnerByStockLocation($stockLocationIds[0]);
				if(count($companyOwners) > 0){
					foreach($companyOwners as  $companyOwner){
						if(!is_null($companyOwner['otrs_user_id'])){
						$otrs->assignUser2Group(USER_SERVICE_ID,$companyOwner['otrs_user_id'], null, $groupId, USER_SERVICE, PASSWORD_SERVICE);
						}
					}
				}
				$instanceUpdate->setOtrsGroup($groupId);
			}
			
			//Process edit instance
			$id = $instanceTable->save($instanceUpdate);
			$stockLocationByInstance = $stockLocationTable->getStockLocationByInstance($instanceId);
			$strLocationIds = '';
			if (false != $arrStockLocationId) {
				if(count($stockLocationByInstance) > 0){
					foreach($stockLocationByInstance as  $si){
						if(!in_array($si['stocklocationid'], $arrStockLocationId)){
							if($strLocationIds == ''){
								$strLocationIds =  $si['stocklocationid'];
							}else{
								$strLocationIds = $strLocationIds.','.$si['stocklocationid'];
							}
						}
					}
				}
			}
			if($strLocationIds != ''){
				$listAlocations = $stockLocationTable->getAllocationByStockLoation($strLocationIds, $instanceId);
				if(count($listAlocations) > 0){
					foreach($listAlocations as $la){
						$stockLocationTable->unAssignHardware($la['destination'], $instanceId, Sss_Ultility_SystemName::ROOMS);
					}
				}
			}
			$arrDeleteId = array(
					'instance = ?' => $instanceId
			);
			$stockLocationInstanceTable->deleteRow(null,$arrDeleteId);
			return $id;
		}
		function checkLoginShepherdDetail($handle,$instance,$instanceId,$account,$accountOvisTable,$instanceTable,$accountTable)
		{
			// Redirect to admin homepage
			$defaultOvisNamespace = new Zend_Session_Namespace(Sss_Ultility_SessionName::OVIS_SHEPHERD_SYSTEM . $handle);
			$defaultOvisNamespace->dbShepherd = $instance->instanceid;
			
			$defaultNamespace = new Zend_Session_Namespace(Sss_Ultility_SessionName::SHEPHERD_SYSTEM . $handle);
			$defaultNamespace->dbShepherd = $instance->instanceid;
			$defaultNamespace->handle = $instance->handle;
			$defaultNamespace->stocklocationId = $instance->stocklocation;
			
			//get user information by session when login
			$userShepherd = new Zend_Session_Namespace(Sss_Ultility_SessionName::ACCOUNT_SESSION_SHEPHERD . $handle);
			
			//get role id by user id
			$roleId = $instanceTable->getRoleByAccount($instance->instanceid, $userShepherd->accountid);
			
			//get role list and assgin to session when check role will be get it
			$roleList = null;
			if($roleId) {
				$roleList = $instanceTable->getByRoleId($instance->instanceid, $roleId->role);
			}
			if($userShepherd->username == Sss_Ultility_CommonViewParamater::USER_NAME_SHEPHERD_DEFAULT) {
				$com = new Sss_Ultility_Common();
				$roleList = $com->defaultListRoleAdministrator();
				//add administrator in shepherd BI
				try {
					$user = $instanceId.$userShepherd->username;
					Sss_Ultility_Common::addUserAndDashboard($user,$account->password,Sss_Ultility_CommonViewParamater::USER_NAME_SHEPHERD_DEFAULT,$instance->instanceid,null,Sss_Ultility_CommonViewParamater::USER_NAME_SHEPHERD_DEFAULT);
				} catch(Exception $e) {
					Sss_Ultility_Common::logger()->log($e, Zend_Log::ERR);
				}
				//End add administrator
			}
			$sessionRoleList  = new Zend_Session_Namespace(Sss_Ultility_SessionName::ROLE_LIST_SESSION . $handle);
			$sessionRoleList->roleList = $roleList;
			$ot = new Sss_Ultility_OtrsServices();
			$userName = $userShepherd->username;
			$password = $account->password;
			$accountTable->checkEsixtedColumns('otrs_user_id', $instanceId);
			if (is_null($account->otrs_user_id)) {
				$arrParams = array();
				$arrParams['fullname'] =  $account->fullname;
				$arrParams['username'] =  $userName . $account->accountid . $handle;
				$arrParams['password'] =  $password;
				$arrParams['email']    =  $account->accountid . $handle.$account->email;
				$arrParams['wsuser']   =  USER_SERVICE;
				$arrParams['wspass']   =  PASSWORD_SERVICE;
				$userOtrsId   = $ot->createCustomerUser(USER_SERVICE_ID, 1, $arrParams);
				if(!is_null($userOtrsId)) {
				$accountUpdate = $accountTable->findById($account->accountid,$instanceId);
				$accountUpdate->setOtrsUserId($userOtrsId);
				$accountTable->save($accountUpdate);
				}
			} else {
				Sss_Ultility_Common::logger()->log($userName . $account->accountid . $handle . '-' . Resources::_('USER_NAME_EXIST'), Zend_Log::ALERT);
			}
			$crrInstances = $instanceTable->getConectedInstanceList($instanceId);
			foreach($crrInstances as $inst) {
				if(is_null($inst['otrs_group'])) {
					$groupId = $ot->createGroup(USER_SERVICE_ID, 1, $handle, '', USER_SERVICE, PASSWORD_SERVICE);
					$ot->addQueue(USER_SERVICE_ID, 1, $handle, $groupId, USER_SERVICE, PASSWORD_SERVICE);
					// Update group id into table Instance
					$instanceUpdate = $instanceTable->findById($instanceId);
					$instanceUpdate->setOtrsGroup($groupId);
					$instanceTable->save($instanceUpdate);
					// Call service of OTRS and update all ovis account to group when add new shepherd instance
					$ovisAccounts = $accountOvisTable->getAccountListByType(Sss_Ultility_Setting::ACCOUNT_OVIS);
					foreach($ovisAccounts as $ao) {
						if(count($ovisAccounts) > 0) {
							if(!is_null($ao['otrs_user_id'])) {
								$ot->assignUser2Group(USER_SERVICE_ID,$ao['otrs_user_id'], null, $groupId, USER_SERVICE, PASSWORD_SERVICE);
							}
						}
					}
					// Assign company owner of instance to OTRS group
					$companyOwners = $accountOvisTable->getCompanyOwnerByStockLocation($inst['stocklocation']);
					if(count($companyOwners) > 0) {
						foreach($companyOwners as  $companyOwner) {
							if(!is_null($companyOwner['otrs_user_id'])) {
								$ot->assignUser2Group(USER_SERVICE_ID,$companyOwner['otrs_user_id'], null, $groupId, USER_SERVICE, PASSWORD_SERVICE);
							}
						}
					}
				} else {
					$groupId = $inst['otrs_group'];
				}
				if(!is_null($groupId)) {
					$ot->assignCustomer2Group(USER_SERVICE_ID, $userName . $account->accountid . $handle, null, $groupId, USER_SERVICE, PASSWORD_SERVICE);
				}
			}
			
			//Create session with url auto login OTRS
			$sessionAutoLoginUrl = new Zend_Session_Namespace(Sss_Ultility_SessionName::SHEPHERD_AUTO_LOGIN_SESSION . $handle);
			$autoLogin =   $ot->autoLogin(USER_SERVICE_ID ,null, $userName . $account->accountid . $handle, $password, "Customer", USER_SERVICE, PASSWORD_SERVICE);
			$sessionAutoLoginUrl->autourl = $autoLogin;
			echo ("<script>var newwin = popupFullScreen('/$handle');newwin.focus();</script>");
		}
		function checkResetShepherdDetail($instanceTable,$instanceId,$resetId,$instance)
		{
			$message = '';
			try {
				$resetAccount = $instanceTable->getAccountByInstance($instanceId, $resetId);
				if($resetAccount != false) {
					if($resetAccount->isactivated == 1) {
						// Redirect to admin homepage
						$handle = $instance->handle;
						$resetActivateCode   = Sss_Ultility_Common::genRandomString(75);
						$resetEmail             = $resetAccount->email;
						$instanceTable->resetAccountofInstance($instanceId, $resetId, $resetActivateCode);
						$subject = Resources::_('SUBJECT_RESET');
						$body    = Resources::_('DEAR').' '.$resetAccount->fullname.',' . " \n \n"
						. Resources::_('BODY1'). " \n \n"
						. Resources::_('BODY2').' '.DOMAIN_SYSTEM."/$handle/active/active?activatecode=$resetActivateCode&popup=1&resetpassword=1". " \n \n"
						. Resources::_('BODY4'). " \n \n"
						. Resources::_('BODY5'). " \n"
						. Resources::_('BODY6');
						Sss_Ultility_Common::sendMail(EMAIL_SYSTEM, $resetEmail, $subject, $body);
						$message = Resources::_('RESET_PASSWORD_SUCCESSFULL');
					}
				}
			}
			catch (exception $e) {
				Sss_Ultility_Common::logger()->log($e, Zend_Log::ERR);
				$message = Resources::_('RESET_PASSWORD_FAIL');
			}
			return $message;
		}
		function autoLoginWhenLoginShepherd($row,$instance)
		{
			$instanceTable = new Application_Model_Mapper_Instance();
			$listAccountIds = '';
			if(count($row) > 0) {
				$arrAutoLogin = array();
				$ot = new Sss_Ultility_OtrsServices();
				foreach ($row as $r) {
					if ($listAccountIds == '' && $r['otrs_user_id'] != '') {
						$listAccountIds = $r['otrs_user_id'];
					} elseif($listAccountIds != '' && $r['otrs_user_id'] == '') {
						$listAccountIds = $listAccountIds;
					} else {
						$listAccountIds = $r['otrs_user_id'].','.$listAccountIds;
					}
				}
				foreach($row as $r) {
					$emailUpdate = $r['accountid'].$instance->handle.$r['email'];
					$userLogin =    $r['username'].$r['accountid'].$instance->handle;
					$ot->updateCustomerUser(USER_SERVICE_ID, 1, $r['fullname'] , $userLogin, $userLogin, $emailUpdate, USER_SERVICE, PASSWORD_SERVICE, $listAccountIds);
					$instanceTable->updateAccount($r['accountid'],$instance->instanceid, $listAccountIds);
					$sessionArrayAutoLoginUrl = new Zend_Session_Namespace(Sss_Ultility_SessionName::SHEPHERD_ARRAY_AUTO_LOGIN_SESSION);
					$autoLogin =   $ot->autoLogin(USER_SERVICE_ID ,null,$r['username'].$r['accountid'].$instance->handle, $r['password'], "Customer", USER_SERVICE, PASSWORD_SERVICE);
					$arrAutoLogin[$r['username']] = $autoLogin;
				}
				$sessionArrayAutoLoginUrl->arrautourl = $arrAutoLogin;
			}
		}
		function setStocklocationList($stockLocationTable,$instance,$instanceId)
		{
			$stockLocationList = '';
			$stockLocationInstance = $stockLocationTable->getStockLocationByInstance($instanceId);
			if($stockLocationInstance) {
				foreach($stockLocationInstance as $s){
					$stockLocationList .= $s['stocklocationname'].'<br/>';
				}
			}
			if($stockLocationList != ''){
				$stockLocationList = substr($stockLocationList, 0, strlen($stockLocationList) - 5);
			}else{
				$stockLocationList = $instance->stocklocationname;
			}
			return $stockLocationList;
		}
		function breadscrumbShepherdDetail($menu)
		{
			//get breadscrumb
			$breadscrumbs = array(
					new Sss_CommonEntity_BreadScrumb($menu, ''),
					new Sss_CommonEntity_BreadScrumb(Resources::_('MY_SHEPHERD'), 'shepherd-instance'),
					new Sss_CommonEntity_BreadScrumb(Resources::_('VIEW_MY_SHEPHERD'), '#')
			);
			return $breadscrumbs;
		}
	}
